import React, { useEffect } from 'react';
import { useMutation } from '@apollo/client';

import NoteForm from '../components/NoteForm';
import { GET_NOTES, GET_MY_NOTES } from '../gql/query';
import { NEW_NOTE } from '../gql/mutation';

const NewNote = props => {
    useEffect(() => {
        document.title = 'New Note —— Notedly';
    });

    const [data, { loading, error }] = useMutation( NEW_NOTE,{
        refetchQueries: [{ query: GET_MY_NOTES },{ query: GET_NOTES }],
        onCompleted: data => {
            //操作完成后，把用户重定向到该篇笔记的页面
            props.history.push(`note/${data.newNote.id}`);
        }
    });

    return (
        <React.Fragment>
            {/*显示一个加载数据的消息 */}
            {loading && <p>Loading...</p>}
            {/*如果出错，显示一个错误消息*/}
            {error && <p>Error saving the note</p>}
            {/*渲染表单组件，通过属性传入变更数据 */}
            <NoteForm action={data} />
        </React.Fragment>
    );
}

export default NewNote;